package com.zhiwei.msf.common.util;

import java.security.SecureRandom;
import java.util.Random;

/**
 * spring oauth2 随机码生成工具
 *
 * @author Ryan Heaton
 * @author Dave Syer
 */
public final class RandomCodeGenerator {

    private RandomCodeGenerator() {
    }

    private static final char[] DEFAULT_CODEC = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
    private static Random random = new SecureRandom();
    private static int length = 4; //随机码长度

    /**
     * 指定随机码长度
     *
     * @param defineLength 随机码长度
     */
    public static void setLength(int defineLength) {
        length = defineLength;
    }

    /**
     * 生成随机码
     */
    public static String generate() {
        byte[] verifierBytes = new byte[length];
        random.nextBytes(verifierBytes);
        return getAuthorizationCodeString(verifierBytes);
    }

    /**
     * Convert these random bytes to a verifier string.
     *
     * @param verifierBytes The bytes.
     * @return The string.
     */
    private static String getAuthorizationCodeString(byte[] verifierBytes) {
        char[] chars = new char[verifierBytes.length];
        for (int i = 0; i < verifierBytes.length; i++) {
            chars[i] = DEFAULT_CODEC[((verifierBytes[i] & 0xFF) % DEFAULT_CODEC.length)];
        }
        return new String(chars);
    }
}